import lodash from 'lodash';

/**
 * 生成唯一字符串，可用于id
 * @param {number} length
 */
export function getUniqueValue (length) {
    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
}
export function uuid (length = 8) {
    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
}
export function isTrue (value) {
    if (value === 0) {
        return true;
    } else if (!!value === false || value === 'false') {
        return false;
    } else {
        return true;
    }
}
/**
 * 判断是否不为undefined/NaN/null/''/false/'false'/{}/[]
 */
export function isReal (value) {
    if (testType(value) === 'Number' && !isNaN(value)) {
        return true;
    } else if (testType(value) === 'Object' && Object.keys(value).length > 0) {
        return true;
    } else if (testType(value) === 'Array' && value.length > 0) {
        return true;
    } else if (!!value === false || value === 'false') {
        return false;
    } else {
        return true;
    }
}
export function stringIsReal (value) {
    if (testType(value) === 'Array') {
        let result = true;
        value.map(item => {
            result = result && stringIsReal(item);
        })
        return result;
    } else {
        return !!value && value != '';
    }
}
/**
 * 判断数据类型
 */
export function testType (value) {
    return Object.prototype.toString.call(value).replace('[object ', '').replace(']', '').toLowerCase();
}
// 格式日期 （例：yyyy年MM月dd日，yyyy-MM-dd hh:mm:ss）
export function formatDate (date, fieldType) {
    var fmt = 'yyyy-MM-dd hh:mm:ss'
    if (fieldType === 'Date') {
        fmt = 'yyyy-MM-dd'
    }
    var o = {
        // 月份
        'M+': date.getMonth() + 1,
        // 日
        'd+': date.getDate(),
        // 小时
        'h+': date.getHours(),
        // 分
        'm+': date.getMinutes(),
        // 秒
        's+': date.getSeconds(),
        // 季度
        'q+': Math.floor((date.getMonth() + 3) / 3),
        // 毫秒
        'S': date.getMilliseconds()
    }
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
    }
    return fmt
}
//删除对象中属性值为空的字段
export function deleteInvalid(filter){
    if(!!filter && filter.constructor===Object){
        for(let key in filter){
            (filter[key]===''||filter[key]===null) && delete filter[key]
        }
    }
}
export function copy(value) {
    if (typeof value !== 'string') return;
    const input = document.createElement('input');

    document.body.appendChild(input);
    input.setAttribute('value', value);
    input.select();
    if (document.execCommand('copy')) {
        document.execCommand('copy');
        console.log('复制成功');
    }
    document.body.removeChild(input);
}

export function getFilter(filterMap){
    let str='';
    if(!!filterMap){
        Object.keys(filterMap).map(key=>{
            let type=typeof filterMap[key];
            if(str==''){
                str=type==='number'||type==='boolean'?`${key}==${filterMap[key]}`:`${key}=='${filterMap[key]}'`
            }else{
                str=type==='number'||type==='boolean'?str+`&&${key}==${filterMap[key]}`:str+`&&${key}=='${filterMap[key]}'`
            }
        })
    };
    return str;
}

export function responsiveSize(size,designWidth=1920){
    const clientWidth = window.innerWidth || document.body.clientWidth
    if(!clientWidth) return
    return clientWidth/designWidth*size
}

export function calcExp($, content) {
    try {
      const sum = (...arg) => { return lodash.sum(arg) }
      const max = (...arg) => { return lodash.max(arg) }
      const min = (...arg) => { return lodash.min(arg) }
      const average = (...arg) => { return lodash.mean(arg) }
      const fn = new Function('$', 'return ' + content);
  
      // fn(data)
      console.log("🚀 ~ file: common.js:114 ~ calcExp ~ fn(data):", $, content)
      // console.log("🚀 ~ file: common.js:114 ~ calcExp ~ fn(data):", fn.call($, this))
      console.log("🚀 ~ file: common.js:114 ~ calcExp ~ fn(data):", eval(content))
      return true
    }
    catch(err) {
      console.log("🚀 ~ file: common.js:113 ~ calcExp ~ err:", err)
      return err
    }
  }
  export function subObject(obj, path,defaultValue) {
    if(!lodash.get(obj,path)){
        if(!!defaultValue){
            lodash.set(obj,path,defaultValue)
        }else{
            return defaultValue;
        }
    }
    const paths = path.split('.');
    let res = obj;
    let tempPath;
    while ((function () { tempPath = paths.shift(); return tempPath; })()) {
      res = res[tempPath];
    }
    return res;
  }
  export function getModelFilter(filterMap, sign = 'like'){
    let arr = [];
    if(!!filterMap){
        Object.keys(filterMap).map(key=>{
            let curItem = filterMap[key]
            let type = typeof curItem;
            let strWrap = (type ==='number' || type ==='boolean') ? "" : "'"

            if (curItem !== '' && curItem !== undefined && curItem !== null) {
                if (sign === 'like' && strWrap && key!='className'&& key!='type'&& key!='id') {
                    arr.push(`${key} like ${strWrap}%${curItem}%${strWrap}`)
                } else {
                    arr.push(`${key} ${"=="} ${strWrap}${curItem}${strWrap}`)
                }
            }
        })
    };
    return arr.join(' && ');
}
export function copyToClipboard(content){
    const textarea = document.createElement('textarea');
    textarea.value = content;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    textarea.remove();
}
export async function copyJsonToClipboard(jsonObj) {
    try {
        const jsonString = JSON.stringify(jsonObj, null, 2); // 转换为格式化的JSON字符串
        await navigator.clipboard.writeText(jsonString); // 将字符串复制到剪贴板
        console.log('JSON已复制到剪贴板');
    } catch (error) {
        console.error('复制到剪贴板时发生错误', error);
    }
}
const common = {
    getUniqueValue, uuid, isTrue, isReal, stringIsReal, testType, formatDate, deleteInvalid,
    copy, getFilter, calcExp, responsiveSize,subObject,getModelFilter,copyToClipboard,copyJsonToClipboard
};
export default common;
